<!--库存查询-->
<template>
  <div class="select-warehouse"> 
    <!-- 搜索条件 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-row class="search-row">
        <el-col :span="4" class="button-group">
          <el-form-item label="货品">
            <el-input v-model="searchForm.name" placeholder="请输入货品名称/编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="button-group">
          <el-form-item label="货品类型">
            <el-tree-select v-model="searchForm.type" :data="types"
                    :props="{
                        value: 'type_id',
                        label: 'type_name',
                        children: 'children'
                    }"
                    placeholder="请选择"
                    style="width: 200px"
                    check-strictly
                    default-expand-all/>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="button-group">
          <el-form-item label="单位">
            <el-select placeholder="请选择" v-model="searchForm.unit" style="width:200px">
                <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="button-group">
          <el-form-item label="仓库名称">
            <el-select v-model="searchForm.whid" placeholder="请选择" clearable style="width: 200px;">
              <el-option v-for="warehouse in warehouses" :key="warehouse.wh_id" :label="warehouse.wh_name" :value="warehouse.wh_id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="search-row">
        <el-col :span="12" class="button-group">
          <el-form-item>
            <el-checkbox v-model="searchForm.showStopped">显示停用商品</el-checkbox>
            <el-checkbox v-model="searchForm.filterZeroStock">过滤零库存</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="search-row">
        <el-col :span="24" class="button-group">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
 
    <!-- 统计信息 -->
    <div class="statistics-container">
      <div class="stat-group">
        <div class="stat-item">
          <span class="stat-value blue-box">{{ statistics.currentStockCount }}</span>
          <span class="stat-label">当前库存数量</span>
        </div>
        <div class="stat-item">
          <span class="stat-value blue-box">¥{{ statistics.currentStockAmount.toFixed(2) }}</span>
          <span class="stat-label">当前库存金额</span>
        </div>
      </div>
      <div class="stat-group">
        <div class="stat-item">
          <span class="stat-value green-box">{{ statistics.inCount }}</span>
          <span class="stat-label">入库数量</span>
        </div>
        <div class="stat-item">
          <span class="stat-value orange-box">{{ statistics.outCount }}</span>
          <span class="stat-label">出库数量</span>
        </div>
      </div>
      <div class="stat-group">
        <div class="stat-item">
          <span class="stat-value green-box">{{ statistics.pendingIn }}</span>
          <span class="stat-label">待入库</span>
        </div>
        <div class="stat-item">
          <span class="stat-value orange-box">{{ statistics.pendingOut }}</span>
          <span class="stat-label">待出库</span>
        </div>
      </div>
    </div>
 
    <!-- 操作按钮 -->
    <div class="action-buttons-left">
      <el-button :loading="exportLoading" @click="handleExport">导出</el-button>
      <el-button @click="fetchData">刷新</el-button>
    </div>
 
    <!-- 表格容器 -->
    <div class="table-container">
        <el-table 
          ref="tableRef"
          :data="tableData" 
          :border="true"
          style="width: 100%"
          v-loading="loading"
           @selection-change="handleSelectionChange"
           row-key="_uniqueId"
        >
        <el-table-column type="selection" width="55" fixed></el-table-column>
        <el-table-column prop="index" label="序号" width="80" fixed></el-table-column>
        <el-table-column prop="proc_code" label="货品编号" width="120" fixed></el-table-column>
        <el-table-column prop="proc_name" label="货品名称" width="120" fixed></el-table-column>
        <el-table-column prop="proc_status" label="状态" width="100" fixed>
        <template #default="scope">
            <el-tag :type="scope.row.proc_status === 0 ? 'success' : 'danger'">
              {{ scope.row.proc_status === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="type_name" label="货品类型" width="120"></el-table-column>
        <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="proc_primary_unit" label="单位" width="100"></el-table-column>
        <el-table-column prop="proc_primary_barcode" label="条码" width="120"></el-table-column>
        <el-table-column prop="wh_name" label="仓库名称" width="120"></el-table-column>
        <el-table-column prop="slot_name" label="库位名称" width="120"></el-table-column>
        <el-table-column prop="proc_inventory" label="当前库存" width="120"></el-table-column>
        <el-table-column prop="proc_inventory_money" label="库存金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.proc_inventory_money.toFixed(2) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" fixed="right">
  <template #default="scope">
    <el-button 
      type="text" 
      size="mini" 
      @click="handleStockDistribution(scope.row)"
      class="link-button"
    >
      库存分布
    </el-button>
  </template>
</el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :page-size="10"
            :pager-count="11"
            layout="prev, pager, next, jumper"
            :total="pagination.total"
            @current-change="handlePageChange"
            style="float:right;margin-top:20px;">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
 
<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '../auth/index';
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx';

export default {
  name: 'StockInventory',
  setup() {
    const customDateRange = ref([])
    const exportLoading = ref(false)
    const loading = ref(false)
    const router = useRouter();
    const selectedRows = ref([]); 

    // 搜索表单
    const searchForm = reactive({
      name: '',
      type: '',
      unit: '',
      whid: null,
      showStopped: false,
      filterZeroStock: false
    })
    
    // 统计数据
    const statistics = reactive({
      currentStockCount: 0,
      currentStockAmount: 0,
      inCount: 0,
      outCount: 0,
      pendingIn: 0,
      pendingOut: 0
    })

    //查询单位
    //查询所有单位
        const units=ref([]);
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res=>{
                units.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }


          //查询所有货品类型绑定到下拉框
        const types=ref([]);
        function AllType(){
            http.get("/ProductType/GetAllProductTypes")
            .then(res=>{
                types.value=convertToTree(res.data);
            }).catch(err=>{
                console.log(err);
            })
        }

         // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
         function convertToTree(data) {
            // 先创建一个以 type_id 为键的映射表，方便快速查找节点
            const map = {};
            data.forEach(item => {
                map[item.type_id] = { ...item, children: [] };
            });
            const tree = [];
            data.forEach(item => {
                const node = map[item.type_id];
                if (item.type_pid === 0) {
                    // 如果是顶层节点，直接添加到树中
                    tree.push(node);
                } else {
                    const parent = map[item.type_pid];
                    if (parent) {
                        // 如果父节点存在，将当前节点添加到父节点的 children 中
                        parent.children.push(node);
                    } else {
                        // 如果父节点不存在，将其作为顶层节点添加到树中
                        tree.push(node);
                    }
                }
            });
            return tree;
        }
    
    // 表格数据
    const tableData = ref([])
    const warehouses = ref([])
    const productTypes = ref([])
    const tableRef = ref(null);
    
    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 1
    })
    
    // 时间标签切换
    const handleTimeTabClick = async (tab) => {
  // 重置分页
  pagination.currentPage = 1;
  
  await fetchData();
};

    // 获取仓库列表
    const fetchWarehouses = async () => {
      try {
        const response = await http.get('/Warehouse/GetWarehouses')
        warehouses.value = response.data
      } catch (error) {
        console.error('获取仓库列表失败:', error)
        ElMessage.error('获取仓库列表失败')
      }
    }

    
    // 获取货品类型列表
    const fetchProductTypes = async () => {
      try {
        const response = await http.get('/ProductType/GetAllProductTypes')
        // 提取所有类型名称（去重）
        const types = [...new Set(response.data.map(item => item.type_name))]
        productTypes.value = types
      } catch (error) {
        console.error('获取货品类型失败:', error)
        ElMessage.error('获取货品类型失败')
      }
    }
    
    // 获取库存数据
    const fetchData = async () => {
      loading.value = true;
      try {
        // 调试日志
        console.log('[获取库存数据] 参数:', {
          name: searchForm.name,
          type: searchForm.type,
          unit: searchForm.unit,
          whid: searchForm.whid,
          showStopped: searchForm.showStopped,
          filterZeroStock: searchForm.filterZeroStock,
          currentPage: pagination.currentPage,
          pageSize: pagination.pageSize
        });
        
        const params = {
          name: searchForm.name,
          type: searchForm.type,
          unit: searchForm.unit,
          whid: searchForm.whid,
          showStopped: searchForm.showStopped,
          filterZeroStock: searchForm.filterZeroStock,
          currentPage: pagination.currentPage,
          pageSize: pagination.pageSize,
        };
        
        const response = await http.get('/Stock/GetStock', { params });

        console.log("库存数据:", response.data?.list);
        
        if (response.data?.list) {
          // 获取到原始数据
          let stockData = response.data.list;
          
          // 如果需要过滤零库存，在前端进行过滤
          if (searchForm.filterZeroStock) {
            stockData = stockData.filter(item => Number(item.proc_inventory) > 0);
          }
          
          const baseTimestamp = Date.now();
          tableData.value = stockData.map((item, index) => {
            const uniqueId = `${baseTimestamp}_${index}_${Math.random().toString(36).substring(2, 15)}`;
            return {
              ...item,
              _uniqueId: uniqueId,
              index: (response.data.currentPage - 1) * response.data.pageSize + index + 1
            };
          });
          
          pagination.currentPage = response.data.currentPage;
          pagination.pageSize = response.data.pageSize;
          pagination.total = response.data.rows;
          
          updateStatistics();
        } else {
          tableData.value = [];
          pagination.total = 0;
        }
      } catch (error) {
        console.error('获取库存数据失败:', error);
        ElMessage.error('获取库存数据失败');
        tableData.value = [];
        pagination.total = 0;
      } finally {
        loading.value = false;
      }
    };
    
    // 更新统计数据
    const updateStatistics = async () => {
      // 更新当前库存数量和金额（模拟数据）
      statistics.currentStockCount = tableData.value.length;
      statistics.currentStockAmount = tableData.value.reduce((sum, item) => sum + (item.proc_inventory_money || 0), 0);

      try {
        // 发起异步请求获取统计数据
        const response = await http.get('/Stock/Gettotal');
        const data = response.data; // 获取响应数据

        // 更新统计数据
        statistics.inCount = data.in_num || 0;          // 入库数量
        statistics.outCount = data.out_num || 0;        // 出库数量
        statistics.pendingIn = data.in_instockNO_num || 0;   // 待入库数量
        statistics.pendingOut = data.out_outstockNO_num || 0; // 待出库数量
      } catch (error) {
        console.error('获取统计数据失败:', error);
        // 如果请求失败，可以设置默认值
        statistics.inCount = 0;
        statistics.outCount = 0;
        statistics.pendingIn = 0;
        statistics.pendingOut = 0;
      }
    };
    
    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchData();
    }
    
    // 重置搜索
    const resetSearch = async () => {
      // 重置表单
      Object.assign(searchForm, {
        name: '',
        type: '',
        unit: '',
        whid: null,
        showStopped: false,
        filterZeroStock: false
      });
      
      // 重置UI状态
      customDateRange.value = [];
      
      // 重新设置默认时间范围
      
      // 强制刷新数据
      pagination.currentPage = 1;
      await fetchData();
    }
    
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection;
    };
    
    // 导出数据
    const handleExport = async () => {
      if (typeof XLSX === 'undefined') {
        ElMessage.error('导出功能依赖的库未加载，请刷新页面重试');
        return;
      }
      
      const selection = selectedRows.value;
      
      if (selection.length === 0 && tableData.value.length === 0) {
        ElMessage.warning('没有可导出的数据');
        return;
      }
      
      exportLoading.value = true;
      try {
        const dataToExport = selection.length > 0 ? selection : tableData.value;
        
        const excelData = dataToExport.map((row, index) => ({
          "序号": row.index || (pagination.currentPage - 1) * pagination.pageSize + index + 1,
          "货品编号": row.proc_code,
          "货品名称": row.proc_name,
          "状态": row.proc_status === 0 ? '停用' : '正常',
          "货品类型": row.type_name,
          "规格型号": row.proc_model,
          "单位": row.proc_primary_unit,
          "条码": row.proc_primary_barcode,
          "仓库名称": row.wh_name,
          "库位名称": row.slot_name,
          "当前库存": row.proc_inventory,
          "库存金额": row.proc_inventory_money ? `¥${row.proc_inventory_money.toFixed(2)}` : '¥0.00',
          "待入库": row.pendingIn || 0,
          "待出库": row.pendingOut || 0,
          "可用库存": row.proc_ky_inventory,
          "可用库存金额": row.proc_ky_inventory_money ? `¥${row.proc_ky_inventory_money.toFixed(2)}` : '¥0.00',
          "期初库存": row.openingStock || 0,
          "期末库存": row.closingStock || 0,
          "入库参考价": row.instock_price ? `¥${row.instock_price.toFixed(2)}` : '¥0.00',
          "出库参考价": row.outstock_price ? `¥${row.outstock_price.toFixed(2)}` : '¥0.00'
        }));
        
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(excelData);
        
        // 设置列宽
        const colWidths = [
          { wch: 8 }, { wch: 15 }, { wch: 20 }, { wch: 10 },
          { wch: 15 }, { wch: 15 }, { wch: 8 }, { wch: 15 },
          { wch: 15 }, { wch: 15 }, { wch: 12 }, { wch: 15 },
          { wch: 10 }, { wch: 10 }, { wch: 12 }, { wch: 15 },
          { wch: 12 }, { wch: 12 }, { wch: 12 }, { wch: 12 }
        ];
        ws['!cols'] = colWidths;
        
        XLSX.utils.book_append_sheet(wb, ws, "库存信息");
        
        const dateStr = new Date().toLocaleDateString().replace(/\//g, '-');
        const fileName = selection.length > 0 
          ? `库存信息_${dateStr}.xlsx`
          : `库存信息_当前页_${dateStr}.xlsx`;
        
        XLSX.writeFile(wb, fileName);
        
        ElMessage.success(selection.length > 0 
          ? `成功导出 ${selection.length} 条选中数据` 
          : `成功导出当前页 ${tableData.value.length} 条数据`);
        
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请重试');
      } finally {
        exportLoading.value = false;
      }
    };
    
    // 分页大小变化
    const handleSizeChange = (val) => {
      pagination.pageSize = val;
      pagination.currentPage = 1;
      fetchData();
    };
    
    // 当前页变化
    const handleCurrentChange = (val) => {
      pagination.currentPage = val;
      fetchData();
    };
    
    // 查看出入库流水
    const handleStockFlow = (row) => {
      router.push('OutInTypeRollup');
    };
    
    // 查看库存分布
    const handleStockDistribution = (row) => {
      router.push('Distribution');
    };
    
    // 初始化加载数据
    onMounted(() => {      
      // 获取基础数据
      fetchWarehouses();
      fetchProductTypes();
      
      // 获取库存数据
      fetchData();
      AllType();
      Getunit();
    });
    
    return {
      customDateRange,
      searchForm,
      statistics,
      tableData,
      warehouses,
      productTypes,
      pagination,
      loading,
      selectedRows,
      handleSelectionChange,
      exportLoading,
      handleTimeTabClick,
      handleSearch,
      resetSearch,
      handleExport,
      handleSizeChange,
      handleCurrentChange,
      handleStockFlow,
      handleStockDistribution,
      fetchData,
      units,
      types
    }
  }
}
</script>
 
<style scoped>
.select-warehouse {
  padding: 20px;
}
 
/* 表格容器样式 */
.table-container {
  width: 100%;
  margin-bottom: 20px;
}
 

 
/* 固定列阴影效果 */
.el-table__fixed, 
.el-table__fixed-right {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.12);
}
 
/* 确保表头和内容对齐 */
.el-table th.gutter,
.el-table td.gutter {
  display: none;
}
 
/* 其他样式保持不变 */
.search-row {
  margin-bottom: 15px;
}
 
.pagination-container {
  text-align: right;
}


.button-group {
  text-align: left;
}
 
.statistics-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 20px;
}
 
.stat-group {
  display: flex;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  flex: 1;
  min-width: 200px;
}
 
.stat-item {
  text-align: center;
  padding: 0 0px;
  flex: 1;
}
 
.stat-value {
  display: block;
  font-size: 24px;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 5px;
}
 
.blue-box {
  color: #409EFF;
  background-color: #fafafa;
}
 
.green-box {
  color: #67C23A;
  background-color: #ffffff;
}
 
.orange-box {
  color: #E6A23C;
  background-color: #fcfcfc;
}
 
.action-buttons-left {
  text-align: left;
  margin-bottom: 20px;
}
.link-button {
  text-decoration: none;
  color: #409EFF;
  padding: 0;
}
 
.link-button:hover {
  text-decoration: none !important;
  color: #66b1ff;
}
 
.link-button + .link-button {
  margin-left: 10px;
}
</style>